package com.ywu.bpmn.flow.service;

import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.bpmn.flow.data.YwuFlowDefinitionRepository;
import com.ywu.bpmn.flow.data.YwuFlowDefinitionVersionRepository;
import com.ywu.bpmn.flow.dto.YwuFlowDefinitionDto;
import com.ywu.bpmn.flow.dto.YwuFlowDefinitionVersionDto;
import com.ywu.bpmn.flow.entity.YwuFlowDefinitionEntity;
import com.ywu.bpmn.flow.entity.YwuFlowDefinitionVersionEntity;
import com.ywu.bpmn.form.service.dto.YwuFormDefinitionVersionDto;
import com.ywu.bpmn.form.service.entity.YwuFormDefinitionEntity;
import com.ywu.bpmn.form.service.service.YwuFormDefinitionService;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.TimerIdGenerateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName YwuFlowDefinitionVersionService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/4/22 17:09
 * @Version 1.0
 **/
@Service
public class YwuFlowDefinitionVersionService {
    @Autowired
    private YwuFlowDefinitionVersionRepository repository;

    @Autowired
    private YwuFlowDefinitionRepository definitionRepository;

    @Autowired
    private YwuFlowDefinitionService service;

    @Autowired
    private YwuFormDefinitionService formDefinitionService;

    /**
     * @Author GroundDemo
     * @Description 查询流程版本列表
     * @Date 18:29 2025/4/22
     * @Param [dto]
     * @return com.ywu.common.result.CommonResult<java.lang.Object>
     **/
    public CommonResult<Object> queryVersionList(YwuFlowDefinitionDto dto) {
        // 校验是否有操作权限（当前租户下是否存在）
        YwuFlowDefinitionEntity queryRes = service.queryEntityByTenantId(dto, false);
        if (Objects.isNull(queryRes)) {
            return CommonResult.error().setErrorCode("id.is.not.exist");
        }
        // 根据resourceId查询所有历史版本
        YwuFlowDefinitionVersionEntity search = new YwuFlowDefinitionVersionEntity();
        search.setResourceId(dto.getId());
        List<YwuFlowDefinitionVersionEntity> versionList = repository.getVersionList(search);
        if (CollectionUtils.isEmpty(versionList)) {
            return CommonResult.success(versionList);
        }
        if (versionList.get(versionList.size() - 1).getVersion() == 0) {
            YwuFlowDefinitionVersionEntity draftVersionEntity = versionList.get(versionList.size() - 1);
            versionList.remove(versionList.size() - 1);
            ArrayList<YwuFlowDefinitionVersionEntity> newList = new ArrayList<>();
            newList.add(draftVersionEntity);
            newList.addAll(versionList);
            versionList = newList;
        }
        return CommonResult.success(versionList);
    }

    /**
     * @Author GroundDemo
     * @Description 删除流程草稿版本
     * @Date 18:29 2025/4/22
     * @Param [dto]
     * @return com.ywu.common.result.CommonResult<java.lang.Object>
     **/
    @Transactional
    public CommonResult<Object> deleteVersion(YwuFlowDefinitionVersionDto dto) {
        if (dto.getVersion() != 0) {
            return CommonResult.error().setErrorCode("version.can.not.delete");
        }
        // 校验是否有操作权限（当前租户下是否存在）
        YwuFlowDefinitionDto searchDto = new YwuFlowDefinitionDto();
        dto.setId(dto.getResourceId());
        YwuFlowDefinitionEntity queryRes = service.queryEntityByTenantId(searchDto, false);
        if (Objects.isNull(queryRes)) {
            return CommonResult.error().setErrorCode("resource.id.is.not.exist")
                    .setMessage("resource id is not exist");
        }
        // 同步删除表单的草稿版本
        YwuFormDefinitionVersionDto ywuFormDefinitionVersionDto = new YwuFormDefinitionVersionDto();
        ywuFormDefinitionVersionDto.setVersion(0);
        ywuFormDefinitionVersionDto.setResourceId(queryRes.getFormId());
        formDefinitionService.deleteVersion(ywuFormDefinitionVersionDto);
        YwuFlowDefinitionVersionEntity delete = new YwuFlowDefinitionVersionEntity();
        delete.setResourceId(dto.getResourceId());
        delete.setVersion(dto.getVersion());
        repository.delete(delete);
        // 修改原始数据的状态
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        queryRes.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        queryRes.setHasNotReleased(0);
        definitionRepository.updateVersionInfo(queryRes);
        return CommonResult.success(null);
    }

    /**
     * @Author GroundDemo
     * @Description 查询历史版本数据
     * @Date 18:55 2025/4/22
     * @Param [dto]
     * @return com.ywu.common.result.CommonResult<java.lang.Object>
     **/
    public CommonResult<Object> queryVersionInfo(YwuFlowDefinitionVersionDto dto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 校验是否有操作权限（当前租户下是否存在）
        YwuFlowDefinitionDto searchDto = new YwuFlowDefinitionDto();
        dto.setId(dto.getResourceId());
        dto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        YwuFlowDefinitionEntity queryRes = service.queryEntityByTenantId(searchDto, false);
        if (Objects.isNull(queryRes)) {
            return CommonResult.error().setErrorCode("resource.id.is.not.exist");
        }
        // 查询版本信息
        YwuFlowDefinitionVersionEntity searchEntity = new YwuFlowDefinitionVersionEntity();
        searchEntity.setResourceId(dto.getResourceId());
        searchEntity.setVersion(dto.getVersion());
        YwuFlowDefinitionVersionEntity versionEntity = repository.getEntity(searchEntity);
        return CommonResult.success(versionEntity);
    }

    /**
     * @Author GroundDemo
     * @Description 回退流程历史版本
     * @Date 18:28 2025/4/22
     * @Param [dto]
     * @return com.ywu.common.result.CommonResult<java.lang.Object>
     **/
    public CommonResult<Object> backVersion(YwuFlowDefinitionVersionDto dto) {
        // 校验是否有操作权限（当前租户下是否存在）
        YwuFlowDefinitionDto searchDto = new YwuFlowDefinitionDto();
        dto.setId(dto.getResourceId());
        YwuFlowDefinitionEntity queryRes = service.queryEntityByTenantId(searchDto, false);
        if (Objects.isNull(queryRes)) {
            return CommonResult.error().setErrorCode("resource.id.is.not.exist");
        }
        if (queryRes.getStatus().equals(YwuFormDefinitionEntity.DRAFT_STATUS)) {
            // 当前操作状态，无法回退
            return CommonResult.error().setErrorCode("draft.status.can.not.back");
        }
        // 查询待回退的历史版本数据
        YwuFlowDefinitionVersionEntity search = new YwuFlowDefinitionVersionEntity();
        search.setResourceId(dto.getResourceId());
        search.setVersion(dto.getVersion());
        YwuFlowDefinitionVersionEntity versionEntity = repository.getEntity(search);
        if (Objects.isNull(versionEntity)) {
            return CommonResult.error().setErrorCode("version.is.not.exist");
        }
        // 同步回退表单的版本
        YwuFormDefinitionVersionDto ywuFormDefinitionVersionDto = new YwuFormDefinitionVersionDto();
        ywuFormDefinitionVersionDto.setVersion(dto.getVersion());
        ywuFormDefinitionVersionDto.setResourceId(queryRes.getFormId());
        formDefinitionService.backVersion(ywuFormDefinitionVersionDto);
        // 删除草稿版本的数据（如果有的话）
        YwuFlowDefinitionVersionEntity deleteDraft = new YwuFlowDefinitionVersionEntity();
        deleteDraft.setResourceId(dto.getResourceId());
        deleteDraft.setVersion(0);
        repository.delete(deleteDraft);
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 添加一条新的草稿数据，数据来源就是之前查询的历史版本的数据
        YwuFlowDefinitionVersionEntity insert = new YwuFlowDefinitionVersionEntity();
        BeanUtils.copyProperties(versionEntity, insert);
        insert.setVersion(0);
        insert.setId(TimerIdGenerateUtil.nextId());
        insert.createInfo(currentContext.getYwuContextUser().getUserAccount());
        repository.insert(insert);
        // 修改原始表中数据hasNotReleased状态为1
        queryRes.setHasNotReleased(1);
        queryRes.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        definitionRepository.updateVersionInfo(queryRes);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询历史版本的流程表单
    * @Date 22:37 2025/4/22
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryFlowFormVersionInfo(YwuFlowDefinitionVersionDto dto) {
        // 校验是否有操作权限（当前租户下是否存在）
        YwuFlowDefinitionDto searchDto = new YwuFlowDefinitionDto();
        searchDto.setId(dto.getResourceId());
        YwuFlowDefinitionEntity queryRes = service.queryEntityByTenantId(searchDto, false);
        if (Objects.isNull(queryRes)) {
            return CommonResult.error().setErrorCode("resource.id.is.not.exist");
        }
        // 根据表单ID和版本查询表单信息
        YwuFormDefinitionVersionDto ywuFormDefinitionDto = new YwuFormDefinitionVersionDto();
        ywuFormDefinitionDto.setResourceId(queryRes.getFormId());
        ywuFormDefinitionDto.setVersion(dto.getVersion());
        CommonResult<Object> result = formDefinitionService.queryVersionEntity(ywuFormDefinitionDto);
        if (Objects.isNull(result) || !"200".equals(result.getCode())) {
            return CommonResult.error().setErrorCode("form.query.info.error");
        }
        return result;
    }
}
